<!-- 其他人的个人信息 -->
<template>
  <div class="others-container">
    <van-nav-bar :left-arrow="true"
                 @click-left="onClickLeft"> </van-nav-bar>

    <van-row class="user-row-style">
      <van-col span="6">
        <van-image round
                   class="avater-style"
                   width="2rem"
                   height="2rem"
                   :src="fromUserInfo.avatar" />
      </van-col>
      <van-col span="16">
        <van-config-provider :theme-vars="themeVars">
          <van-cell center
                    :label="'id:'+fromUserInfo.id"
                    :value="fromUserInfo.motto">
            <template #title>
              <span>{{fromUserInfo.realName}}</span>
              <van-icon name="https://b.yzcdn.cn/vant/icon-demo-1126.png" />
            </template>
          </van-cell>
        </van-config-provider>
      </van-col>
    </van-row>

    <van-row class="user-row-style">
      <van-col span="24">
        <!-- 其他用户临时聊天信息  -->
        <div class="temp-chat-style">
          <!-- 循环下面的数据 -->
          <div class="from-style"
               v-for="(chatMsg, index) in chatMsgs"
               :key="index">
            <span class="name-style">{{chatMsg.fromName}}：</span>
            <span class="msg-style">{{chatMsg.content}}</span>
          </div>
          <div class="return-back-style">
            <span @click="toggleDialogClick">回复</span>
          </div>
        </div>
      </van-col>

    </van-row>

    <div class="setting-style">
      <van-cell is-link
                center
                class="top-cell"
                clickable
                to="/contact/new-friend">
        <!-- 使用 title 插槽来自定义标题 -->
        <template #title>
          <van-icon name="shrink" />
          <span class="custom-title">圈子</span>
        </template>
      </van-cell>
    </div>

    <van-dialog v-model:show="showDialog"
                title="回复"
                confirm-button-text="发送"
                show-cancel-button
                @confirm="sendReturnBackMessage"
                @cancel="cancelClick">
      <van-field v-model="returnBackContent"
                 autosize
                 clearable
                 type="textarea"
                 maxlength="50"
                 placeholder="请输入回复信息"
                 show-word-limit
                 @clear="clearContent" />

    </van-dialog>
  </div>
</template>

<script>
import { Toast } from 'vant';
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
    //这里存放数据
    return {
      // 展示回复框
      showDialog: false,
      themeVars: { cellLabelMarginTop: "0.3rem" },
      // 对方的用户基本信息，用户名，头像，座右铭等
      fromUserInfo: {},
      // 聊天消息
      chatMsgs: [],
      // 当前打开的用户唯一标识
      fromIdentity: '',
      // 回复消息内容
      returnBackContent: '',
    };
  },
  //方法集合
  methods: {
    // 初始化数据
    init () {
      var that = this;
      // 获取用户基础信息
      that.$http
        .get(that.$reqPrefix.user + "/users/" + that.fromIdentity, {}).then(res => {
          that.fromUserInfo = res.data;
          //请求消息对话数据
          that.$http
            .get(that.$reqPrefix.im + "/im/users/" + that.fromIdentity + "/temp-chat-message/list", {}).then(res0 => {
              if (res0.data) {
                res0.data.forEach((message) => {
                  var chatMsg = {
                    "fromName": message.fromName,
                    "content": message.content
                  };
                  if (message.fromIdentity === that.fromIdentity) {
                    chatMsg.fromName = res.data.realName;
                  } else {
                    chatMsg.fromName = '我';
                  }
                  that.chatMsgs.push(chatMsg);
                });
              }
              //构建总线监听
              that.$emitter.on('onmessage', that.onmessage);
            }).catch(err0 => {
              Toast.fail(err0.data.message);
            });
        }).catch(err => {
          Toast.fail(err.data.message);
        });
    },
    onClickLeft () {
      this.$router.go(-1);
    },
    // 展示关闭对话框
    toggleDialogClick () {
      this.showDialog = true;
    },
    // 清空返回框内容
    clearContent () {
      this.returnBackContent = '';
    },
    // 取消发送
    cancelClick () {
      this.clearContent();
    },
    // 发送回复信息
    sendReturnBackMessage () {
      if (this.returnBackContent) {
        // 从缓存中取出socket 对象进行调用send() 方法来发送
        const socket = this.$store.state.socket;
        if (socket) {
          // 封装添加好友的消息类型
          let pChatMessage = new proto.com.ouyu.im.Message();
          pChatMessage.setFrom(this.$socket.config.identity)
          pChatMessage.setTo(this.fromIdentity)
          pChatMessage.setContentType(SOCKET_CONSTANT.PACKET.MESSAGE_CONTENT_TYPE.TEXT_CONTENT);
          pChatMessage.setContent(this.returnBackContent);
          // 时间戳毫秒
          pChatMessage.setCreateTime(new Date().getTime());
          socket.send(pChatMessage, SOCKET_CONSTANT.PACKET.MESSAGE_TYPE.IM_FRIEND_ADD_REQ);
          // 追加数据到当前聊天中
          this.chatMsgs.push({
            "fromName": '我',
            "content": this.returnBackContent
          });
        } else {
          Toast.fail("无效连接！")
        }
        this.clearContent();
      } else {
        Toast.fail("请输入有效字符！")
      }

    },
    // 消息监听
    onmessage: function (data) {
      // 如果是好友请求，则进行消息处理
      if (data.messageType === SOCKET_CONSTANT.PACKET.MESSAGE_TYPE.IM_FRIEND_ADD_REQ) {
        var that = this;
        var identity = data.message.getFrom();
        // 转成string 字符串
        var lasterLeavingMessage = data.message.getContent();
        // 判断发送者是否是当前打开的该用户，如果是则进行处理，不是则忽略
        if (identity === that.fromIdentity) {
          that.chatMsgs.push({
            "fromName": that.fromUserInfo.realName,
            "content": lasterLeavingMessage
          });
        }
      }
    }
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
    // 获取页面传递的数据信息
    this.fromIdentity = this.$route.params.identity;
    this.init();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () { },
  //生命周期 - 创建之前
  beforeCreate () { },
  //生命周期 - 挂载之前
  beforeMount () { },
  //生命周期 - 更新之前
  beforeUpdate () { },
  //生命周期 - 更新之后
  updated () { },
  //生命周期 - 销毁之前
  beforeUnmount () { },
  //生命周期 - 销毁完成
  unmounted () {
    //销毁监听
    this.$emitter.off('onmessage', this.onmessage);
  },
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated () { },
};
</script>
<style lang="less" scoped>
//@import url(); 引入公共css类
.others-container {
  position: absolute;
  height: 100%;
  width: 100%;
  background: whitesmoke;
}
.avater-style {
  margin-left: 16px;
}
.user-row-style {
  border-bottom: 1px solid #f7f8fa;
  background-color: #ffffff;
}
.top-cell /deep/ .van-cell__title {
  display: flex;
  align-items: center;
}
.setting-style {
  margin-top: 0.3rem;
}
.custom-title {
  display: inline-flex;
  align-items: center;
  height: 100%;
  margin-left: 10px;
}
.temp-chat-style {
  position: relative;
  height: 3rem;
  margin: 0.4rem 0.6rem 0.8rem 0.6rem;
  background: whitesmoke;
  border-radius: 0.2rem;
  overflow: auto;
  padding: 0.2rem 0.3rem;
  .from-style {
    line-height: 0.5rem;
    border-bottom: 1px solid #f7f8fa;
  }
  .return-back-style {
    margin-bottom: 0.2rem;
    position: sticky;
    overflow: auto;
    bottom: 0px;
    color: #0000cc;
  }
}
</style>
